<template>
    <view class="page">
        <view class="context">
            <view class="context-header"></view>
            <view class="context-info" v-if="feedbackset.customershow">
                <view class="context-title">
                    {{ feedbackset.customer }} {{ feedbackset.customerrequired ? '（必填）' : '' }}
                </view>
                <view>
                    <custom-textarea height="75" :maxlength="16383" v-model="CustomerFeedback"></custom-textarea>
                </view>
                <view class="context-voice">
                    <view class="context-voice-mic" v-if="CustomerFeedbackvoice"
                        @click="play(CustomerFeedbackvoice, 0)">
                        <uv-icon custom-prefix="custom-icon" labelColor="#000000" color="#ffffff"
                            :name="playing === 0 ? lujing : bofang" size="14"></uv-icon>
                    </view>
                    <view class="context-voice-mic" @click="() => { toch = true; popup.open() }">
                        <uv-icon color="#ffffff" name="mic" size="22"></uv-icon>
                    </view>
                </view>
            </view>

            <view class="context-info" v-if="feedbackset.methodshow">
                <view class="context-title">
                    {{ feedbackset.method }} {{ feedbackset.methodrequired ? '（必填）' : '' }}
                </view>
                <view>
                    <custom-textarea height="75" :maxlength="16383" v-model="results"></custom-textarea>
                </view>
                <view class="context-voice">
                    <view class="context-voice-mic" v-if="resultsvoice" @click="play(resultsvoice, 1)">
                        <uv-icon custom-prefix="custom-icon" labelColor="#000000" color="#ffffff"
                            :name="playing === 1 ? lujing : bofang" size="14"></uv-icon>
                    </view>
                    <view class="context-voice-mic" @click="() => { toch = false; popup.open() }">
                        <uv-icon color="#ffffff" name="mic" size="22"></uv-icon>
                    </view>
                </view>
            </view>

            <view class="context-info" v-if="feedbackset.usershow">
                <view class="context-title" v-if="feedbackset.methodshow">
                    用户信息 {{ feedbackset.userrequired ? '（必填）' : '' }}
                </view>
                <view>
                    <custom-textarea height="75" :maxlength="16383" v-model="customerremarks"></custom-textarea>
                </view>
            </view>

            <view class="context-info">
                <view class="context-title">
                    {{ $t('图片及视频') }}
                </view>
                <view>
                    <uploadfile v-model="resultsFile" accept="media" @delete="deleteresultsFile"></uploadfile>
                </view>
            </view>

            <view class="context-end">
                <uv-button :custom-style="submitButton" @click="submit" :text="$t('提交')"></uv-button>
            </view>
        </view>
    </view>
    <uv-popup ref="popup" mode="bottom" bgColor="none">
        <view class="popup-view">
            <view>
                <uv-avatar size="84" :src="!Recording ? '/static/image/liyin2.png' : '/static/image/luyin4.png'"
                    @touchstart="startRecord(toch)" @touchend="endRecord"></uv-avatar>
                <view class="popup-text">长按录音</view>
            </view>
        </view>
    </uv-popup>
</template>

<script setup lang="ts">
import api, { apiget, uploadFile } from '@/api';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { onMounted, ref } from 'vue';
import uploadfile from '../../components/uploadfile.vue';
import dayjs from 'dayjs';
import { useI18n } from 'vue-i18n';
import { submitButton } from '@/util/style';
import { lujing, bofang } from '@/util/data';
import CustomTextarea from '@/components/custom-textarea.vue';
const $t = useI18n().t
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
const id = ref()
const resultsFile = ref<any[]>([])
const results = ref()
const CustomerFeedback = ref()
const customerremarks = ref()

const toch = ref(true)

const popup = ref()

const playing = ref(-1)
/**
 * 反馈语音
 */
const CustomerFeedbackvoice = ref()
/**
 * 处理语音
 */
const resultsvoice = ref()
const comment = ref<Eps.BaseUserCommentEntity>()
const feedbackset = ref({
    customer: '顾客反馈',
    customershow: 1,
    customerrequired: 1,
    method: '处理方法和结果',
    methodshow: 1,
    methodrequired: 1,
    usershow: 0,
    userrequired: 0,
})
onLoad((query) => {
    api<any[]>('/wechat/feedbackset/list').then(c => {
        if (c[0]) {
            feedbackset.value = c[0]
        }
    })
    id.value = query?.id
    start()
})

async function submit() {
    if (feedbackset.value.customershow && feedbackset.value.customerrequired) {
        if (CustomerFeedback.value || CustomerFeedbackvoice.value) {

        } else {
            uni.showToast({
                title: $t('顾客反馈（必填）'),
                icon: 'error',
                duration: 2000
            })
            return
        }
    }
    if (feedbackset.value.methodshow && feedbackset.value.methodrequired) {
        if (results.value || resultsvoice.value) {

        } else {
            uni.showToast({
                title: $t('处理方法和结果（必填）'),
                icon: 'error',
                duration: 2000
            })
            return
        }
    }
    if (feedbackset.value.usershow && feedbackset.value.userrequired) {
        if (!customerremarks.value) {
            uni.showToast({
                title: $t('用户信息（必填）'),
                icon: 'error',
                duration: 2000
            })
            return
        }
    }
    if (comment.value?.identifycomment) {
        if (comment.value.identifycomment.feedbacktime1) {
            comment.value.identifycomment.feedbacktimeconsuming = dayjs(comment.value.identifycomment.feedbacktime1).unix() - dayjs(comment.value.identifycomment.identifytime).unix()
        }
    }

    await api('/wechat/identifycomment/update', {
        ...comment.value?.identifycomment,
        comment: {
            id: id.value,
            CustomerFeedback: CustomerFeedback.value,
            results: results.value,
            resultsFile: resultsFile.value,
            resultstime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            CustomerFeedbackvoice: CustomerFeedbackvoice.value,
            resultsvoice: resultsvoice.value,
            state: '完成',
            customerremarks: customerremarks.value
        },
    }).then(() => {
        uni.showToast({
            title: $t('反馈成功'),
            duration: 2000,
        });
        uni.navigateBack()
    }).catch(e => {
        uni.showToast({
            title: $t('反馈失败'),
            duration: 2000,
            icon: 'error'
        });
    })
}


function deleteresultsFile(c: { name: string, index: number }) {
    resultsFile.value.splice(c.index, 1)
}

const index = ref(false)

function play(src: string, index: number) {
    console.log(index === playing.value)
    if (index === playing.value) {
        innerAudioContext.stop()
    } else {
        innerAudioContext.stop()
        playing.value = index
        innerAudioContext.src = src
        innerAudioContext.play()
    }
}

onMounted(() => {
    recorderManager.onStop(function (res) {
        if (res.duration < 500) {
            uni.showToast({
                title: $t('录音太短'),
                icon: 'error'
            })
        } else {
            console.log(res)
            uploadFile({
                size: res.fileSize,
                thumb: res.tempFilePath,
                type: 'aac',
                url: res.tempFilePath
            }).then(c => {
                if (index.value) {
                    CustomerFeedbackvoice.value = c.url
                } else {
                    resultsvoice.value = c.url
                }
            }).catch(f => {
                console.log(f)
            })
        }

    });

    innerAudioContext.onStop(e => {
        playing.value = -1
    })
    innerAudioContext.onEnded(() => {
        playing.value = -1

    })
})

onUnload(() => {
    innerAudioContext?.destroy()
})

async function start() {
    comment.value = await apiget('/wechat/comment/info', {
        id: id.value
    })
    CustomerFeedback.value = comment.value?.CustomerFeedback
    results.value = comment.value?.results
    resultsFile.value = comment.value?.resultsFile || []
    resultsvoice.value = comment.value?.resultsvoice
    CustomerFeedbackvoice.value = comment.value?.CustomerFeedbackvoice
    customerremarks.value = comment.value?.customerremarks

}

const Recording = ref(false)

function startRecord(i: boolean) {
    index.value = i
    Recording.value = true
    console.log('开始录音');
    uni.showToast({
        title: '录音中',
        image: '/static/image/luyin.png',
        duration: 600000,
        position: 'top'
    })
    recorderManager.start({
        duration: 60000,
    });
}

function endRecord() {
    console.log('录音结束');
    uni.hideToast()
    popup.value.close()
    Recording.value = false
    recorderManager.stop();
}


</script>


<style scoped lang="scss">
.context {
    display: flex;
    flex-direction: column;
    width: 100%;
    gap: 12rpx;
    font-size: 14px;
    color: #666666;

    .context-header {
        height: 12rpx;
    }

    .context-info {
        padding-left: 32rpx;
        padding-right: 32rpx;
        display: flex;
        flex-direction: column;
        gap: 12rpx;

        .context-title {
            font-weight: 600;
            color: #000000;
        }

        .context-voice {
            display: flex;
            flex-wrap: wrap;
            align-content: center;
            justify-content: flex-end;
            height: 60rpx;
            gap: 12px;

            .context-voice-mic {
                width: 32px;
                height: 32px;
                border-radius: 8px;
                background-color: rgba(253, 117, 76, 1);
                text-align: center;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
    }

    .context-end {
        padding: 32rpx;
        display: flex;
        align-content: center;
        justify-content: center;
    }
}

.popup-view {
    height: 300rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100vw;

    .popup-text {
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>